package com.helei.web.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CaptchaGenerator {

    //private static final int WIDTH = 200;
   // private static final int HEIGHT = 70;
   // private static final int CODE_LENGTH = 4;
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    /**
     * 生成图片验证码
     * @param captchaCode 验证码
     * @param x 验证码位置
     * @param y 验证码位置
     * @param width 验证码宽度
     * @param height 验证码高度
     * @return
     */
    public static BufferedImage generateCaptcha(String captchaCode, Integer x, Integer y, int width,int height) {
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();

        // 设置背景色
        // graphics.setColor(Color.LIGHT_GRAY);
        Color whiteColor = getWhiteColor();
        graphics.setColor(whiteColor);
        graphics.fillRect(0, 0, width, height);

        // 设置字体
        graphics.setFont(new Font("Arial", Font.BOLD, 40));

        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
        }

        // 绘制验证码字符
        for (int i = 0; i < captchaCode.length(); i++) {
            graphics.setColor(getRandomColor());
            graphics.drawString(String.valueOf(captchaCode.charAt(i)), x + (i * 40), y);
        }

        graphics.dispose();
        return bufferedImage;
    }

    public static String generateCaptchaCode(int codeLength) {
        StringBuilder captchaCode = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < codeLength; i++) {
            int index = random.nextInt(CHARACTERS.length());
            captchaCode.append(CHARACTERS.charAt(index));
        }
        return captchaCode.toString();
    }

    private static Color getRandomColor() {
        Random random = new Random();
        return new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255));
    }

    private static Color getWhiteColor() {
        return new Color(255, 255, 255);
    }
}
